//
//  InspectionDetailVC.swift
//  Employee
//
//  Created by swordjoy on 2017/4/11.
//  Copyright © 2017年 remotevillage. All rights reserved.
//

import UIKit

class InspectionDetailVC: BaseVC {
    // 判断从哪里进来
    var isFromHome: Bool = false
    
    var recordId: String!
    var status: String!
    var selectDate: Date!
    var isCooperate: Bool!
    var inspectionTime: String!
    var parentVC: UIViewController?

    
    fileprivate var tableView: UITableView!
    fileprivate var qrScanButton: UIButton!
    fileprivate var detailModel: InspectionDetailModel?
  
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = GlobalConfig.BGWhiteColor

        create()
        pullData()
    }
  
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        GlobalConfig.baiduStatisticsPageViewStart("巡检详情")
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        GlobalConfig.baiduStatisticsPageViewEnd("巡检详情")
    }
}

// MARK: - action

extension InspectionDetailVC {
  
    @objc fileprivate func qrScanAction() {
        let vc = GlobalConfig.qrCodeController { (qrCode) in
            if qrCode.sj.isNumber() {
            let vc = WriteInspectionVC()
            vc.isFromFunc = !self.isFromHome
            vc.regionNumber = qrCode
            vc.parentVC = self.parentVC
            self.navigationController?.pushViewController(vc, animated: true)
            return
            }

            if qrCode.sj.isURL() {
            let webVC = WebViewController(url: URL(string: qrCode)!)
            self.navigationController?.pushViewController(webVC, animated: true)
            return
            }

            let resultVC = ScanResultVC()
            resultVC.result = qrCode
            self.navigationController?.pushViewController(resultVC, animated: true)
        }
        self.navigationController?.pushViewController(vc, animated: true)
    }
  
}

// MARK: - fileprivate

extension InspectionDetailVC {
  
    fileprivate func pullData() {
        SJApp.showHUD()
        let _ = WorkorderRequest.shared.getInspectionDetail(recordId: recordId, status: status) { (detailModel) in
            self.detailModel = detailModel
            self.detailModel?.isCooperate = self.isCooperate
            self.detailModel?.inspectionTime = self.inspectionTime
            runOnMainThread {
                self.tableView.reloadData()
            }
        }
    }
  
    fileprivate func create() {
        addBackItem()

        tableView = UITableView()
        tableView.backgroundColor = UIColor.clear
        tableView.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.noNavBarHeight)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.register(OrderTitleCell.self, forCellReuseIdentifier: OrderTitleCell.identifier)
        tableView.register(InspectionDetailCell.self, forCellReuseIdentifier: InspectionDetailCell.identifier)
        tableView.register(ShowImageViewCell.self, forCellReuseIdentifier: ShowImageViewCell.identifier)
        view.addSubview(tableView)

        if "WaitInspection" == status && selectDate.inLocalRegion().isToday {
            tableView.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.noNavBarHeight - 60)

            qrScanButton = UIButton(frame: CGRect(x: 10, y: UIScreen.noNavBarHeight - 60, width: UIScreen.width - 20, height: 50))
            qrScanButton?.setTitle("扫码巡检", for: .normal)
            qrScanButton?.setTitleColor(UIColor.white, for: .normal)
            qrScanButton?.backgroundColor = GlobalConfig.BGSkyBlueColor
            qrScanButton?.layer.cornerRadius = 4
            qrScanButton?.clipsToBounds = true
            qrScanButton?.addTarget(self, action: #selector(qrScanAction), for: .touchUpInside)
            self.view.addSubview(qrScanButton!)
        }
    }
  
}

// MARK: - UITableViewDataSource
extension InspectionDetailVC : UITableViewDataSource {
  
    func numberOfSections(in tableView: UITableView) -> Int { return 2 }
  
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        guard let temp = detailModel else { return 0 }

        if 0 == section { return 1 }
        else { return temp.result.count }
    }
  
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if 0 == indexPath.section {
            let cell = tableView.dequeueReusableCell(withIdentifier: OrderTitleCell.identifier) as! OrderTitleCell
            cell.inspecttionDetailModel = detailModel
            return cell
        }
        else {
            let model = detailModel?.result[indexPath.row] ?? nil
            if model?.style == "Image" {
                let cell = tableView.dequeueReusableCell(withIdentifier: ShowImageViewCell.identifier) as! ShowImageViewCell
                if let datas = model?.value {
                    cell.models = datas
                }
                if let name = model?.name {
                    cell.titleName = name
                }
                cell.cellDidClick = { [unowned self] (index, collectionView) in
                    guard let temps = model?.value else {
                        return
                    }
                    
                    var images: [SJImageModel] = []
                    for (index, item) in temps.enumerated() {
                        if let cell = collectionView.cellForItem(at: IndexPath(row: index, section: 0)) as? ImageSelectCell {
                            let image = SJImageModel(thumb: cell.imageV, thumb: cell.imageV.image, original: item)
                            images.append(image)
                        }
                        else {
                            let image = SJImageModel(thumb: nil, thumb: nil, original: item)
                            images.append(image)
                        }
                    }
                    
                    let viewer = ImageViewer(images: images, presentingVC: self)
                    viewer.show(index: index)
                }
                cell.mainView.snp.updateConstraints { (make) in
                    make.top.equalTo(5)
                }
                return cell
            }
            let cell = tableView.dequeueReusableCell(withIdentifier: InspectionDetailCell.identifier) as! InspectionDetailCell
            cell.model = model
            return cell
        }
    }
}

// MARK: - UITableViewDelegate
extension InspectionDetailVC : UITableViewDelegate, UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView.contentOffset.y > UIScreen.navBarHeight {
            self.title = detailModel?.areaName
        } else {
            self.title = ""
        }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if 0 == indexPath.section { return OrderTitleCell.heightWithTitle(model: detailModel!) }
        else {
            let model = detailModel?.result[indexPath.row] ?? nil
            if model?.style == "Image" {
                var height: CGFloat = 0
                if (model?.value) != nil {
                    height = (UIScreen.width - 100) / 4
                }
                
                return height + 55
            }
            return InspectionDetailCell.height(with: model!)
            
        }
    }
}
